<template>
  <div class="sales-order-page">
    <n-grid :cols="24">
      <n-grid-item span="24">
        <detail-page-header title="销售订单详情">
          <n-button
            type="primary"
            class="flex items-center"
            @click.stop="handleClickkAddPayment"
          >
            <span>支付</span>
          </n-button>
          <n-button type="primary" @click.stop="handleComplete"
            >完成订单</n-button
          >
        </detail-page-header>
        <div class="mt-[16px]"></div>
        <n-grid :col="24" x-gap="10">
          <n-grid-item span="14">
            <n-card>
              <n-h3>
                <span class="mr-2">#{{ salesInfo.num }}</span>
                <DictTag
                  v-if="salesInfo.status"
                  dict="pos_purchase_status"
                  :value="salesInfo.status"
                />
              </n-h3>
              <div class="flex items-center">
                <n-icon><TimeOutline /></n-icon>
                <span class="ml-1">创建时间：{{ salesInfo.createTime }}</span>
              </div>
              <div class="mt-[16px]"></div>
              <n-card size="small">
                <div class="mb-2">
                  <span class="font-bold text-base">销售清单</span>
                </div>
                <!-- ITEMS -->
                <div
                  class="purchase-item"
                  v-for="item in salesItems"
                  :key="item.id"
                >
                  <div class="flex">
                    <div class="flex-1 flex justify-between mr-10">
                      <span>{{ item.name }}</span>
                      <span>{{ item.quantity }}</span>
                    </div>
                    <div class="text-right">
                      <span>{{ currencyFormat(item.rowSubtotal) }}</span>
                    </div>
                  </div>
                  <template
                    v-if="item.hasSerialNumber === '1' && item.sns.length"
                  >
                    <div
                      class="flex justify-between items-center mt-1"
                      v-for="snItem in item.sns"
                      :key="snItem.id"
                    >
                      <div>
                        <span>序列号/IMEI：</span>
                        <span>{{ snItem.snName }}</span>
                      </div>
                      <n-button
                        type="success"
                        secondary
                        size="small"
                        @click.stop="handleGetSnCheckResult(snItem)"
                      >
                        <template #icon>
                          <n-icon><List /></n-icon>
                        </template>
                      </n-button>
                    </div>
                  </template>
                </div>
                <template #action>
                  <div class="flex justify-between">
                    <span class="font-bold text-base">订单总金额：</span>
                    <span class="font-bold text-base">
                      {{ currencyFormat(salesInfo.total) }}
                    </span>
                  </div>
                </template>
              </n-card>
            </n-card>
          </n-grid-item>
          <n-grid-item span="10">
            <n-card>
              <n-h3>客户信息</n-h3>
              <div class="mt-[16px]">
                <n-grid :cols="24" :x-gap="10" :y-gap="10">
                  <n-grid-item span="12">
                    <div class="flex items-center text-sm text-gray-500">
                      <n-icon><Person /></n-icon><span class="ml-1">姓名</span>
                    </div>
                    <div class="text-base mt-1">
                      <span>{{ customerInfo.name }}</span>
                    </div>
                  </n-grid-item>
                  <n-grid-item span="12">
                    <div class="flex items-center text-sm text-gray-500">
                      <n-icon><PhonePortraitOutline /></n-icon
                      ><span class="ml-1">联系电话</span>
                    </div>
                    <div class="text-base mt-1">
                      <span>{{ customerInfo.phoneNumber }}</span>
                    </div>
                  </n-grid-item>
                  <n-grid-item span="12">
                    <div class="flex items-center text-sm text-gray-500">
                      <n-icon><Mail /></n-icon><span class="ml-1">邮箱</span>
                    </div>
                    <div class="text-base mt-1">
                      <span>{{ customerInfo.email || "/" }}</span>
                    </div>
                  </n-grid-item>
                </n-grid>
              </div>
            </n-card>
            <div class="mt-[10px]"></div>
            <n-card>
              <n-h3>支付信息</n-h3>
              <div class="mb-2 flex justify-between items-center">
                <span class="font-bold text-base">已支付金额：</span>
                <span class="font-bold">
                  {{ currencyFormat(salesInfo.paidAmount) }}
                </span>
              </div>
              <!-- PAYMENT ITEM -->
              <div
                class="payment-item"
                v-for="item in paymentsList"
                :key="item.id"
              >
                <div>
                  <div class="desc">
                    <span>支付订单编号：</span>
                    <span class="payment-num">#{{ item.id }}</span>
                  </div>
                  <div class="amount">
                    <span>
                      {{ getPaymentMethodName(item.method) }} -
                      {{ currencyFormat(item.amount) }}
                    </span>
                  </div>
                  <div class="desc mt-1">
                    <span>{{ item.createTime }}</span>
                  </div>
                </div>
                <div>
                  <img
                    class="w-[48px]"
                    :src="getPaymentAsset(`${item.method}.png`)"
                  />
                </div>
              </div>
            </n-card>
          </n-grid-item>
        </n-grid>
      </n-grid-item>
    </n-grid>
    <!-- 问题清单弹窗 -->
    <CheckResultModal
      :title="checkResultTitle"
      :checkResultList="checkResultList"
      v-model:show="showCheckResult"
      @close="showCheckResult = false"
      :show-footer="false"
    >
      <template v-slot:name="{ checkResult }">
        {{ checkResult.questionName }}
      </template>
    </CheckResultModal>
    <!-- 添加支付方式弹窗 -->
    <PaymentModal
      title="选择支付方式"
      payment-title="待支付金额"
      :payment-methods="paymentMethods"
      :total-price="dueAmount"
      :confirm-loading="paymentConfirmLoading"
      :check-equels="false"
      v-model:show="showPayment"
      @cancel="handleHidePayment"
      @close="handleHidePayment"
      @confirm="handleConfirmAddPayment"
    />
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import { debounce, get } from "lodash-es";
import Big from "big.js";
import {
  TimeOutline,
  List,
  Person,
  PhonePortraitOutline,
  Mail,
} from "@vicons/ionicons5";
import {
  getPaymentAsset,
  getPaymentMethodName,
} from "@/common/utils/payment/index";
import { currencyFormat } from "@/common/utils/currencyFormatter/index.ts";
import DictTag from "@/components/biz/dictTag/index.vue";
import {
  usePaymentModal,
  PaymentModal,
} from "@/components/biz/paymentModal/index.ts";
import { DictStorage } from "@/storage/dict.storage";
import {
  getSalesOrderDetail,
  addSalesPayment,
  completeOrder,
} from "@/api/sales/sales.api";
import { getSnCheckResult } from "@/api/inventory/inventory.api";
import { ISalesOrderDetailProps } from "./props";
import {
  PosSalesItemSns,
  SalesOrderDetailVO,
} from "@/types/model/sales/vos/sales.vo";
import {
  useCheckResultModal,
  CheckResultModal,
} from "@/components/biz/checkResultModal/index.ts";

const paymentMethods = DictStorage.getDictItemsByCode(
  "pos_tradein_payment_method"
);

const props = defineProps<ISalesOrderDetailProps>();

const { showCheckResult, checkResultList, checkResultTitle } =
  useCheckResultModal();

const {
  modalShowFlag: showPayment,
  handleShowModal: handleShowPaymentModal,
  handleHideModal: handleHidePaymentModal,
} = usePaymentModal();

const paymentConfirmLoading = ref<boolean>(false);
const orderDetail = ref<SalesOrderDetailVO>({} as SalesOrderDetailVO);

const canAddPayment = computed<boolean>(() => {
  const status = get(orderDetail.value, "posSales.status");
  return status === "unpaid";
});

const dueAmount = computed(() => {
  const total = get(orderDetail.value, "posSales.total") || 0;
  const paidAmount = get(orderDetail.value, "posSales.paidAmount") || 0;
  return new Big(total).minus(paidAmount).toNumber();
});

const salesInfo = computed(() => {
  return get(orderDetail.value, "posSales") || {};
});

const salesItems = computed(() => {
  return get(orderDetail.value, "items") || [];
});

const customerInfo = computed(() => {
  return get(orderDetail.value, "posCustomer") || {};
});

const paymentsList = computed(() => {
  return get(orderDetail.value, "payments") || [];
});

const handleGetOrderDetail = async (orderId: string) => {
  const result = await getSalesOrderDetail(orderId);
  orderDetail.value = result.result;
};

const handleGetSnCheckResult = async (snItem: PosSalesItemSns) => {
  if (snItem.snId) {
    const result = await getSnCheckResult(snItem.snId);
    console.log(result);
    showCheckResult.value = true;
    checkResultTitle.value = `序列号/IMEI: ${snItem.snName}的问题清单`;
    checkResultList.value = get(result, "result") || [];
  }
};

const handleClickkAddPayment = () => {
  handleShowPaymentModal();
};

const handleConfirmAddPayment = debounce(async function (
  paymentMethods: any[]
) {
  const salesId = get(orderDetail.value, "posSales.id") || "";
  if (!salesId) {
    return;
  }
  const params = {
    salesId,
    paymentItems: paymentMethods.map((item) => {
      return {
        method: item.paymentMethod,
        amount: item.amount,
      };
    }),
  };
  const result = await addSalesPayment(params);
  console.log(result);
});

const handleHidePayment = () => {
  if (!paymentConfirmLoading.value) {
    handleHidePaymentModal();
  }
};

const handleComplete = () => {
  completeOrder(props.id);
};

onMounted(() => {
  handleGetOrderDetail(props.id);
});
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
